package com.winit.common.servlet;

import java.io.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.winit.common.util.ConfigUtil;
import com.winit.common.util.Constants;
import com.winit.common.util.SpringContextHolder;
import com.winit.core.ci.vcs.exception.VCSException;
import com.winit.deploy.util.DeployFileUtil;
import com.winit.jumpServer.manager.JumpServerManager;
import com.winit.jumpServer.task.PushStatusEnum;
import com.winit.project.core.bean.PackageTypeEnum;
import com.winit.project.core.bean.ProjectInfo;
import com.winit.project.core.branch.Project;
import com.winit.project.core.branch.ProjectStatus;
import com.winit.project.manager.ProjectManager;
import com.winit.project.task.BuildStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InitConfigServlet extends HttpServlet {

	private static Logger logger = LoggerFactory.getLogger(InitConfigServlet.class);
	
	public InitConfigServlet() {
		super();
	}

	/**
	 * Initialization of the servlet.
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		logger.info("初始化信息开始...");
		this.runShell();
		/**
		 * 加载跳板机信息
		 */
		JumpServerManager jumpServerManager = SpringContextHolder.getBean(JumpServerManager.class);
		jumpServerManager.loadJumpInfo();
		/**
		 * 检出svn config文件
		 */
		try {
			File file = new File(Constants.CONFIG_REPOSITORY_PATH);
			if(file.exists()){
				Constants.CONFIG_REPOSITORY_SVN.doUpdate();
			}else{
				Constants.CONFIG_REPOSITORY_SVN.doCheckOut();
			}
		} catch (VCSException e) {
			e.printStackTrace();
			logger.error("检出svn config文件异常,e:"+e.getMessage());
		}

		/**
		 * 清空所有非停机发版状态
		 */
		DeployFileUtil.cleanEnvStatus();

		//清空工程构建状态
		ProjectManager projectManager=SpringContextHolder.getBean(ProjectManager.class);
		BuildStatusEnum status = BuildStatusEnum.BUILD_FAILED;
		try {
			List<ProjectInfo> list = projectManager.getProjectList(PackageTypeEnum.ALL, false, true);
			for (ProjectInfo info:list){
				Project project = new Project(info.getProjectName(),true);
				ProjectStatus projectStatus = project.getProjectStatus();

				String buildStatus = projectStatus.getBuildStatus();
				if(BuildStatusEnum.IN_QUEUE.getDesc().equals(buildStatus)
						|| BuildStatusEnum.ON_BUILD.getDesc().equals(buildStatus)){
					logger.info("修改工程构建状态,projectName="+info.getProjectName()+",buildStatus="+buildStatus);
					project.updateBuildStatus(status,info.getProjectName());
					project.updateDependencyProjectStatus(status);
				}
				if(PushStatusEnum.IN_PUSH.getDesc().equals(projectStatus.getPushStatus())){
					project.updatePushStatus(PushStatusEnum.PUSH_ERROR,"tomcat停止,推送失败!",projectStatus.getPushEdition());
					File file = new File(project.getPath());
					for (File f:file.listFiles()){
						if(!f.getName().startsWith("push_")){
							continue;
						}
						f.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		logger.info("初始化信息结束...");
	}

	private void runShell(){
		StringBuffer filePath = new StringBuffer();
		filePath.append(Constants.SHELL_PATH).append("shell/init/beetle_init.sh");
		String[] param = new String[3];
		param[0] = "bash";
		param[1] = filePath.toString();
		param[2] = ConfigUtil.getValue("rootPath");
		try {
			Process process = Runtime.getRuntime().exec(param);
			BufferedInputStream in = new BufferedInputStream(process.getInputStream());  
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;
			while ((line=br.readLine()) != null ) {
				logger.info("执行beetle_init.sh，返回："+line);
			}
			br.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("执行beetle_init.sh成功！");
	}
	
	@Override
	public void destroy() {
		super.destroy();
	}
}
